package dnl.proj.rami;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Daniel Orr
 */
public class GroovyTextManipulationExecutor {

    public String convert(String s) throws IOException {
        String groovyCode = getConversionCode();
        Map<String, Object> args = new HashMap<>();
        args.put("s", s);
        return (String) executeGroovy(groovyCode, args);
    }

    private String getConversionCode() throws IOException {
        final String userHome = System.getProperty("user.home");
        File f = new File(userHome, "rami.groovy");
        if (!f.exists()){
            final InputStream is = getClass().getResourceAsStream("conversion1.groovy");
            FileUtils.copyInputStreamToFile(is, f);
        }
        try {
            return FileUtils.readFileToString(f);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Object executeGroovy(String groovyCode, Map<String, Object> args) throws IOException {
        Binding binding = new Binding();
        for (String identifier : args.keySet()) {
            final Object argumentValue = args.get(identifier);
            binding.setVariable(identifier, argumentValue);
        }
        GroovyShell shell = new GroovyShell(binding);
        return shell.evaluate(groovyCode);
    }

    public static void main(String[] args) throws IOException {
        GroovyTextManipulationExecutor g = new GroovyTextManipulationExecutor();
        final String c = g.convert("123 abc");
        System.out.println(c);
    }
}
